#include "EnemyManager.h"
#include "Enemy.h"
#include "MainLayer.h"
#include "EffectFactory.h"
#include "Effect.h"
#include "EffectDefine.h"
#include "EnemyDefine.h"


EnemyManager::EnemyManager(void)
{
	_timeDelayEnemy = 0;
	_curTimeDelayEnemy = 0;
}


EnemyManager::~EnemyManager(void)
{
}

bool EnemyManager::init()
{
	if (!CCNode::init())
		return false;

	_timeDelayEnemy = 0.5f;
	
	return true;
}

/*
- Check if enemy be outside and remove it
- Check if enemy died -> explosive effect -> remove it
*/
void EnemyManager::enemyProcessing( float dt )
{
	CCArray* listEnemy = getMainLayer()->getEnemies();
	CCArray* listToDeleteEnemy = CCArray::create();
	CCArray* listEnemyDie = CCArray::create();
	CCObject* it;
	float speedUpFactor = getMainLayer()->getMap()->getSpeedUpFactor();
	
	// Check enemy outside && plane
	PlayerPlane* plane = getMainLayer()->getMyPlant();
	CCARRAY_FOREACH(listEnemy, it)
	{
		Enemy* enemy = dynamic_cast<Enemy*>(it);
		enemy->updatePosition(dt * speedUpFactor);
		if (enemy->boundingBox().getMaxY() < 0)
		{
			listToDeleteEnemy->addObject(enemy);
		}

		if (enemy->getHealth() < 0)
			listEnemyDie->addObject(enemy);

		// Check collision enemy & plane
		if (plane->getIsProtected())
		{
			CCRect boundBox = plane->boundingBox();
			CCSize extract = plane->getProtectBoundBox();
			CCRect protectBox = CCRectMake(boundBox.origin.x - extract.width, boundBox.origin.y - extract.height,
											boundBox.size.width + 2 * extract.width ,boundBox.size.height + 2 * extract.height);
			if (enemy->boundingBox().intersectsRect(protectBox))
				enemy->setHealth(-1);
			
		} else
		{
			if (enemy->boundingBox().intersectsRect(plane->boundingBox()))
				plane->setHealth(-1);
		}
// 		if (enemy->boundingBox().intersectsRect(plane->boundingBox()))
// 		{
// 			if (plane->getIsProtected())
// 			{
// 				enemy->setHealth(-1);
// 			} else {
// 				plane->setHealth(-1);
// 			}
// 		}
	}
	// Delete out side enemy
	CCARRAY_FOREACH(listToDeleteEnemy, it)
	{
		getMainLayer()->removeEnemy(dynamic_cast<Enemy*>(it));
	}
	// Process list enemies died
	CCARRAY_FOREACH(listEnemyDie, it)
	{
		//
		Enemy* enemy = dynamic_cast<Enemy*>(it);
		enemy->onDie();
		getMainLayer()->removeEnemy(enemy);
		
		//
		Effect* ef = EffectFactory::sharedEffectFactory()->createEffect(EXPLOSIVE_1);
		ef->setPosition(ccp(enemy->boundingBox().getMidX(), enemy->boundingBox().getMidY()));
		getMainLayer()->getEffectManager()->addEffect(ef);
	}
}

MainLayer* EnemyManager::getMainLayer() 
{
	return dynamic_cast<MainLayer*>(getParent());
}


void EnemyManager::onEnter()
{
	CCNode::onEnter();
	schedule(SEL_SCHEDULE(&EnemyManager::enemyProcessing));
}

void EnemyManager::onExit()
{
	CCNode::onExit();
	unschedule(SEL_SCHEDULE(&EnemyManager::enemyProcessing));
}
